package com.shawn.dubbo.utils;

import com.shawn.model.mongo.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

/**
 * pid自增工具类
 *
 * @author lenovo
 * @date 2022/10/28
 */
@Component
public class IdWorker {

    @Autowired
    private  MongoTemplate mongoTemplate;

    public  Long getNextId(String collName) {
        //根据collName字段进行查询
        Query query = new Query(Criteria.where("collName").is(collName));

        Update update = new Update();
        //对查询的行的seqId进行自增操作
        update.inc("seqId", 1);

        FindAndModifyOptions options = new FindAndModifyOptions();
        //如果找到即更新
        options.upsert(true);
        //返回最新生成pid字段
        options.returnNew(true);

        Sequence sequence = mongoTemplate.findAndModify(query,update,options,Sequence.class);
        //返回seqId 作为Movement 推送使用的pid
        return sequence.getSeqId();
    }
}
